﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace 视频设备
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                生成验证码 ma = new 生成验证码();
                var str = ma.GenerateCheckCode();
                CreateCheckCodeImage(str);
            }
        }


        //生成图片
        public void CreateCheckCodeImage(string code)
        {
            var imageCode = new System.Drawing.Bitmap((int)Math.Ceiling((code.Length * 12.5)), 23); //定义图片的宽度和高度 
            var g = Graphics.FromImage(imageCode); //加载图片到画布上 
            try
            {
                var random = new Random();
                g.Clear(Color.White); //清空图片背景色 
                //画图片的背景噪音线 
                for (int i = 0; i < 25; i++)
                {
                    var x1 = random.Next(imageCode.Width);
                    var x2 = random.Next(imageCode.Width);
                    var y1 = random.Next(imageCode.Height);
                    var y2 = random.Next(imageCode.Height);
                    g.DrawLine(new Pen(Color.Silver), new Point(x1, y1), new Point(x2, y2));
                }
                var font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic);
                var brush = new System.Drawing.Drawing2D.LinearGradientBrush(
                new Rectangle(0, 0, imageCode.Width, imageCode.Height),
                Color.Blue, Color.DarkRed, 1.2F, true);
                g.DrawString(code, font, brush, 2, 2);
                //画图片的前景噪音点 
                for (int i = 0; i < 100; i++)
                {
                    var x = random.Next(imageCode.Width);
                    var y = random.Next(imageCode.Height);
                    imageCode.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线 
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, imageCode.Width - 1, imageCode.Height - 1);
                var ms = new System.IO.MemoryStream();
                imageCode.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                Response.ClearContent();
                Response.ContentType = "image/Jpeg";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                imageCode.Dispose();
            }
        }
    }
}